package com.xmg.boot.demo.bootlesson1.user.intercept;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xmg.boot.demo.bootcommon.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ma
 * @CreateTime: 2023-11-23
 * @Description: JWT拦截器
 * @Version: 1.0
 */
@Component
public class JWTInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Logger log= LoggerFactory.getLogger(JWTInterceptors.class);

        //跨域请求会首先发一个option请求，直接返回正常状态并通过拦截器
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");

        Map<String,Object> map = new HashMap<>();
        String token = request.getHeader("token");
        //response.sendRedirect(request.getContextPath()+"/login");
        if(StringUtils.isEmpty(token)){
            map.put("msg","token为空");
        }
        else{
            try {
                JwtUtils.verify(token);
                return true;
            } catch (SignatureVerificationException e) {
                log.error("无效签名！ 错误 ->", e);
                map.put("msg","无效签名！");
            } catch (TokenExpiredException e) {
                log.error("token过期！ 错误 ->", e);
                map.put("msg","token过期！");
            } catch (AlgorithmMismatchException e) {
                log.error("token算法不一致！ 错误 ->", e);
                map.put("msg","token算法不一致！");
            } catch (Exception e) {
                log.error("token无效！ 错误 ->", e);
                map.put("msg","token无效！");
            }
        }
        map.put("code","1001");
        //map转JSON
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }
}
